<template>

	<div class="indexDetail">
		<el-breadcrumb separator="/" class="bread-title">
			<el-breadcrumb-item :to="{ path: '/indexPopupManage' }">首页弹框管理</el-breadcrumb-item>
			<el-breadcrumb-item v-if="pageType==='add'">新增</el-breadcrumb-item>
			<el-breadcrumb-item v-if="pageType==='edit'">编辑</el-breadcrumb-item>
		</el-breadcrumb>
		<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px" class="demo-ruleForm">
			<el-form-item label="APP" prop="type" required>
				<span v-if="pageType == 'edit'">
					{{ruleForm.type == 0 ? '经纪人端': ''}}
					{{ruleForm.type == 1 ? '好房端': ''}}
					{{ruleForm.type == 2 ? '管家端': ''}}
				</span>
				<el-select v-model="ruleForm.type" class="w-260" v-if="pageType=='add'">
					<el-option v-for="item in originList" :label="item.label" :value="item.id" :key="item.id"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="排序"  prop="order" required>
				<el-input v-model="ruleForm.order" class="w-260"></el-input>
				<span class="hint">注意，英文下划线区分；举例：1_2_3_5_4</span>
			</el-form-item>
			<div class="line"></div>	
			<div v-for="(item,index) in ruleForm.details">
				<el-form-item :label="'图片' + (index+1)" prop="item" :class="{'star' : index == 0}">
					<upLoadImg v-model="item.img" :picindex="index" @uploadSuccess="uploadSuccess" ref="uploadNode"></upLoadImg>
					<span class="hint">限制数量1，格式为jpg，大小1M以内，长宽建议270px*324px</span>
				</el-form-item>
				<el-form-item :label="'链接'+(index+1)" :prop="'details.'+index+'.url'" :rules="detailsRules.detailsurl" :class="{'star' : index == 0}">
					<el-input v-model="item.url" class="w-400"></el-input>
				</el-form-item>
				<div class="line"></div>		
			</div>
			<el-form-item>
				<el-button type="primary" @click="submitForm('ruleForm')" v-if="pageType === 'add'">新建并启用</el-button>
				<el-button type="primary" @click="submitForm('ruleForm')" v-if="pageType === 'edit'">保存并启用</el-button>
			</el-form-item>
		</el-form>
	</div>
	
</template>

<script>
import api from '@/api/apiPath'
import upLoadImg from './components/uploadOneImg'

export default {
	components: {upLoadImg},
	data() {
		var checksort = (rule, value, callback) => {
			if (!value) {
				return callback(new Error('请输入排序！'));
			} 
			setTimeout(() => {
				// 下划线不能连接 不能下划线开始和结束  数字不能重复   /^[1-5_]+$/
				let reg = /^(?!.*([1-5]).*\1)[1-5](_[1-5])*$/;
				// let reg = /^[1-5](_[1-5])*$/;
				if (!reg.test(value)) {
					callback(new Error('只允许1-5数字和英文下划线！数字不能重复,下划线不能连接'));
				}
				else{
					callback();
				}
			}, 500);
		};

		var checklink = (rule, value, callback) => {
			let reg = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
			if(!reg.test(value)){
				callback(new Error('链接不合法！'));
			}else{
				callback();
			}
		}
		return {
			createOperator:Number,
			createOperatorName:'',//创建人
			createOperatorPhone:'',//
			createTime:Number,//创建时间
			pageType: '',//类型 编辑 新增	
			ruleForm: {
				id: "", //数据ID 字符串类型
				type: 1, // app类型 0为经纪人端  1为好房端   2为管家端
				order:'',//排序
				details:[
				{'img':'', 'url':''},
				{'img':'', 'url':''},
				{'img':'', 'url':''},
				{'img':'', 'url':''},
				{'img':'', 'url':''}
				],
				sort:[],
			},
			originList: [
				{id: 0, label: '经纪人端'},
				{id: 1, label: '好房端'},
				{id: 2, label: '管家端'},
			],
			detailsRules:{
 				// detailsurl:[{required: false,  validator: checklink, trigger: 'blur'}]
 			},
 			rules: {
 				order: [
 				{ validator: checksort, trigger: 'blur' }
 				]
 			 },
 			}
 		},
 		mounted () {
 			if(this.pageType == 'edit'){
 				this.axios.get(api.POPWINDOWSEE + this.$route.query.id).then(res => {
 					let editobj = res.data.data;
 					this.ruleForm.order = editobj['sort'].join('_');
 					this.ruleForm.type = editobj['type'];
 					this.ruleForm.id = editobj['id'];
 					this.createOperator = editobj['createOperator'];
 					this.createOperatorName = editobj['createOperatorName'];
 					this.createOperatorPhone = editobj['createOperatorPhone'];
 					this.createTime = editobj['createTime'];
 					this.ruleForm.details = editobj.details.concat(this.ruleForm.details).slice(0,5)
 				})
 			}
 		},
 		created () {
 			this.pageType = this.$route.query.type;
 		},
 		methods: {
 			uploadSuccess (data) {
 				if(data.state == 'add'){
 					this.ruleForm.details.forEach(function(item,index,array){
 						if (data.index == index ) {
 							item.img = data.url
 						}
 					})
 				}else if(data.state == 'del'){
 					this.ruleForm.details.forEach(function(item,index,array){
 						if (data.index == index ) {
 							item.img = ""
 						}
 					})
 				}
 			},
 			submitForm(formName) { 	
 				this.$refs[formName].validate((valid) => {
 					if (valid) {
 						let objs = {};
 						objs['sort'] = this.ruleForm.order.split('_').map(item => {  
 							return parseInt(item); 
 						});

 						if (this.pageType === 'edit') {
 							objs.id = this.ruleForm.id;
 							objs.createOperator = this.createOperator;
 							objs.createOperatorName = this.createOperatorName;
 							objs.createTime	= this.createTime;
 							objs.createOperatorPhone = this.createOperatorPhone;
 						}
 						objs.type = parseInt(this.ruleForm.type);
 						objs.details = this.ruleForm.details;
 						let obj = {}
 						obj.homePage = objs;

 						if(objs.details.length == 0){
 							this.$message.success('请至少上传1张图片和至少输入1个正确的链接地址！')
 							return
 						}
 						if(objs.details[0].img == '' || !objs.details[0].img){
 							this.$message.success('请上传图片1信息！')
 							return
 						}
 						if(objs.details[0].url == '' || !objs.details[0].url){
 							this.$message.success('请输入链接1信息！')
 							return
 						}
 						let express = /^(http(s)?:\/\/)?(www\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+(:\d+)*(\/\w+\.\w+)*/;
 						if (!express.test(objs.details[0].url)) {
 							this.$message.success('链接不合法！')
 							return
 						}
 						for (let i =0; i < objs.details.length; i++) {
						//验证所有url填写是否合法
						if (objs.details[i].url != '' && !express.test(objs.details[i].url)) {
							this.$message.success( "链接"+(i+1)+"不合法!")
							return
						}
						//图片和链接需要成对出现
						if(objs.details[i].img == '' && objs.details[i].url != ''){
							this.$message.success( `请完善图片${i+1}信息!`)
							return
						}else if(objs.details[i].img != '' && objs.details[i].url == ''){
							this.$message.success( `请完善链接${i+1}信息!`)
							return
						}
					}

					if (this.pageType === 'edit') {
						this.$confirm(`确定对商品做修改？`, '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消'
						}).then(() => {
							if (!this.ruleForm.id){
								this.$message({
									type: 'info',
									message: 'id不能为空'
								});
								return;
							}
							this.axios.post(api.POPWINDOWEDIT, obj).then(res => {
								this.$message.success('修改成功')
								this.$router.push({path: '/indexPopupManage'})
							})

						}).catch(() => {
							this.$message({
								type: 'info',
								message: '已取消'
							});
						});
					} else {
						this.$confirm(`确定创建该商品？`, '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消'
						}).then(() => {
							this.axios.post(api.POPUPWINDOWSAVE, obj).then(res => {
								this.$message.success('创建成功')
								this.$router.push({path: '/indexPopupManage'})
							})
						}).catch(() => {
							this.$message({
								type: 'info',
								message: '已取消'
							});
						});
					}
				} else {
					return false;
				}
			});
 			},
 		}
 	}
 	
 	</script>


 	<style lang="stylus">
 	.line{
 		border-top: 1px solid rgba(7, 17, 27, .1);
 		padding: 10px 0;
 	}
 	.star > .el-form-item__label:before{
 		content:"*"
 		color:red;
 		margin-right: 2px;
 	}
 	</style>
